<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message, Result, Button, Space } from '@arco-design/web-vue'
import { distroShortLinkUsingGet, resolveShortLinkUsingGet } from '@/api/linkController'
import { IconUserGroup, IconClose } from '@arco-design/web-vue/es/icon'
import { acceptInviteUsingPost, resolveInviteUsingGet } from '@/api/teamController'
import { useUserStore, useTeamStore } from '@/store'

const userStore = useUserStore()
const teamStore = useTeamStore()
const route = useRoute()
const router = useRouter()

const loading = ref(true)
const error = ref<string>('')

// 邀请信息
const inviteInfo = ref<{
  inviterName: string
  teamName: string
  teamId: number
  inviterId: number
} | null>(null)

// 添加响应状态
const responseStatus = ref<'pending' | 'accepted' | 'rejected'>('pending')

// 解析短链
const parseShortLink = async () => {
  try {
    const url = window.location.href
    const res: any = await resolveShortLinkUsingGet({ url })
    console.log(res)
    if (res.code === 0 && res.data) {
      const parsedUrl = new URL(res.data)

      // 判断链接类型
      if (parsedUrl.pathname.startsWith('/team/invite')) {
        // 解析团队邀请链接参数
        const params = new URLSearchParams(parsedUrl.search)
        const inviterId = Number(params.get('inviterId'))
        const teamId = Number(params.get('teamId'))

        // 检查是否是自己发出的邀请
        if (inviterId === userStore.user?.id) {
          error.value = '不能接受自己发出的邀请'
          return
        }

        // 检查是否已经在团队中
        const isInTeam = teamStore.teamUserVoList?.some((team) => team.id === teamId)
        if (isInTeam) {
          error.value = '您已经是该团队成员'
          return
        }

        inviteInfo.value = {
          inviterName: params.get('inviterName') || '未知用户',
          teamName: params.get('name') || '未知团队',
          teamId,
          inviterId
        }
      } else {
        error.value = '不支持的链接类型'
      }
    } else {
      error.value = res.message || '链接解析失败'
    }
  } catch (e: any) {
    error.value = e.message || '链接解析失败'
  } finally {
    loading.value = false
  }
}

// 修改处理邀请响应
const handleInviteResponse = async (accept: boolean) => {
  if (!inviteInfo.value) return
  const url = window.location.href
  try {
    if (accept) {
      const res: any = await resolveInviteUsingGet({ url })
      if (res.code === 0) {
        responseStatus.value = 'accepted'
      } else {
        Message.error(res.message || '加入失败')
      }
    } else {
      await distroShortLinkUsingGet({ url })
      responseStatus.value = 'rejected'
    }
  } catch (e: any) {
    Message.error(e.message || '操作失败')
  }
}

// 修改关闭页面的方法
const handleClose = () => {
  // 如果是通过 window.open 打开的页面，可以关闭
  if (window.opener) {
    window.close()
  } else {
    // 如果是直接打开的页面，跳转到首页
    router.push('/')
  }
}

// 页面加载时立即解析
onMounted(async () => {
  await parseShortLink()
})
</script>

<template>
  <div class="short-link-page">
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <div class="loading-text">正在解析链接...</div>
    </div>

    <Result v-else-if="error" status="error" :subtitle="error">
      <template #extra>
        <Button @click="() => router.push('/')">返回首页</Button>
      </template>
    </Result>

    <!-- 团队邀请确认 -->
    <div v-else-if="inviteInfo" class="invite-container">
      <Result
        :status="responseStatus === 'rejected' ? 'error' : 'info'"
        class="invite-content"
      >
        <template #icon>
          <div class="invite-icon">
            <IconClose v-if="responseStatus === 'rejected'" />
            <IconUserGroup v-else />
          </div>
        </template>
        <template #title>
          <span class="invite-text" v-if="responseStatus === 'pending'">
            <span class="highlight-name">{{ inviteInfo.inviterName }}</span>
            邀请您加入团队
            <span class="highlight-name">{{ inviteInfo.teamName }}</span>
          </span>
          <span v-else-if="responseStatus === 'rejected'" class="response-text">
            您已拒绝该邀请
          </span>
          <span v-else class="response-text">
            您已同意加入团队
          </span>
        </template>
        <template #extra>
          <Space size="medium" v-if="responseStatus === 'pending'">
            <Button status="danger" @click="handleInviteResponse(false)">拒绝</Button>
            <Button type="primary" status="success" @click="handleInviteResponse(true)">同意</Button>
          </Space>
          <Button v-else type="primary" @click="handleClose">关闭页面</Button>
        </template>
      </Result>
    </div>
  </div>
</template>

<style scoped>
.short-link-page {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--color-fill-2);
}

.loading-container {
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 16px;
  border: 3px solid var(--color-fill-3);
  border-top-color: var(--color-primary-6);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: var(--color-text-2);
  font-size: 14px;
}

.invite-container {
  background: var(--color-bg-2);
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.invite-icon {
  font-size: 48px;
  color: var(--color-error-6);  /* 拒绝状态使用错误色 */
}

.invite-content {
  text-align: center;
}

.invite-text {
  font-size: 18px;
  color: var(--color-text-2);
}

.highlight-name {
  color: var(--color-primary-6);
  font-weight: 600;
  font-size: 20px;
  margin: 0 4px;
  transition: color 0.3s ease;
}

.highlight-name:hover {
  color: var(--color-primary-5);
  text-shadow: 0 0 8px rgba(var(--primary-6), 0.2);
}

.response-text {
  font-size: 18px;
  color: var(--color-text-1);
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
